const OrderModel = require('../models/orderModel');
const OrderDetailModel = require('../models/orderDetailModel');
const CartModel = require('../models/cartModel');
const UserModel = require('../models/userModel');

const createOrder = async (req, res) => {
  try {
    const userId = req.user.id;
    const cartItems = await CartModel.getCartItems(userId);

    if (!cartItems.length) {
      return res.status(400).json({ error: 'Cart is empty' });
    }

    const user = await UserModel.getUserById(userId);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    const totalAmount = cartItems.reduce((sum, item) => sum + parseFloat(item.subtotal), 0);

    // 检查用户虚拟货币是否足够
    if (user.virtual_currency < totalAmount) {
      return res.status(400).json({ error: '货币不足!' });
    }

    // 创建订单
    const order = await OrderModel.createOrder(userId, totalAmount, 'virtual_currency');
    

    //扣除用户虚拟货币，传入负数金额
    await UserModel.updateVirtualCurrency(userId, -totalAmount);

    // 扣除用户虚拟货币后增加获取最新用户数据的逻辑
    const updatedUser = await UserModel.getUserById(userId);

    // 将购物车商品移动到订单详情
    const orderDetails = cartItems.map(item => ({
      order_id: order.order_id,
      item_id: item.item_id,
      quantity: item.quantity,
      price: parseFloat(item.product_price)
    }));

    await OrderDetailModel.addOrderDetails(orderDetails);

    // 清空购物车
    await CartModel.clearCart(userId);

    res.status(200).json({
      order,
      userBalance: updatedUser.virtual_currency, // 新增返回字段
      message: 'Order created successfully'
    });
  } catch (error) {
    console.error('Error in createOrder:', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
};
const getOrderDetails = async (req, res) => {
  try {
    const { orderId } = req.params;
    const order = await OrderModel.getOrderById(orderId);
    
    if (!order) {
      return res.status(404).json({ error: 'Order not found' });
    }
    
    const details = await OrderDetailModel.getOrderDetails(orderId);
    res.status(200).json({ order, details });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

const getUserOrders = async (req, res) => {
  try {
    const userId = req.user.id;
    const orders = await OrderModel.getUserOrders(userId);
    res.status(200).json(orders);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

const cancelOrder = async (req, res) => {
  try {
    const { orderId } = req.params;
    const cancelledOrder = await OrderModel.cancelOrder(orderId);
    
    if (!cancelledOrder) { // 确保这里检查正确
      return res.status(404).json({ error: 'Order not found' });
    }
    
    // 返回标准化成功响应
    res.status(200).json({ 
      success: true,
      message: '订单取消成功',
      order: cancelledOrder // 返回更新后的订单
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ 
      success: false,
      error: error.message || 'Internal Server Error' 
    });
  }
};


module.exports = { createOrder, getOrderDetails, getUserOrders, cancelOrder };